package com.dobby.logger.business.dao.impl;

import com.dobby.logger.business.dao.BizLogDao;
import com.dobby.logger.business.entity.BizLog;
import com.dobby.logger.common.BaseDao;
import com.dobby.logger.common.OpenPage;
import com.dobby.logger.constants.Message;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.deser.ValueInstantiators;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by liguoqing on 2016/3/7.
 */
@Repository("bizLogDao")
public class BizLogDaoImpl extends BaseDao implements BizLogDao {


    @Override
    public OpenPage<BizLog> get(Map<String, String> conditionMap, OpenPage<BizLog> openPage) {
        String companyId = conditionMap.get("companyId");
        String operatorType = conditionMap.get("operatorType");
        String ipAddress = conditionMap.get("ipAddress");
        String moduleId = conditionMap.get("moduleId");
        String applicationId = conditionMap.get("applicationId");
        String visible = conditionMap.get("visible");
        String datetimeStart = conditionMap.get("datetimeStart");
        String datetimeEnd = conditionMap.get("datetimeEnd");
        String content = conditionMap.get("content");

        StringBuilder sql = new StringBuilder(" select id,company_id,operator_id,operator_type,operate_date,content,application_id,module_id,ip_address,visible");
        sql.append(" from t_biz_log where 1=1 ");
        List<Object> argList = Lists.newArrayList();

        if(!Strings.isNullOrEmpty(companyId)) {
            sql.append(" and company_id = ? ");
            argList.add(companyId);
        }
        if (!Strings.isNullOrEmpty(ipAddress)) {
            sql.append(" and ip_address = ? ");
            argList.add(ipAddress);
        }
        if (!Strings.isNullOrEmpty(operatorType)) {
            sql.append(" and operator_type = ? ");
            argList.add(operatorType);
        }
        if (!Strings.isNullOrEmpty(applicationId)) {
            sql.append(" and application_id like ? ");
            argList.add("%" + applicationId + "%");
        }
        if(StringUtils.isNotBlank(content)) {
            sql.append(" and content like ?");
            argList.add("%" + content + "%");
        }
        if (!Strings.isNullOrEmpty(moduleId)) {
            sql.append(" and module_id like ? ");
            argList.add("%" + moduleId + "%");
        }
        if (!Strings.isNullOrEmpty(visible)) {
            sql.append(" and visible = ? ");
            argList.add(visible);
        }
        if(!Strings.isNullOrEmpty(datetimeStart) && !Strings.isNullOrEmpty(datetimeEnd)) {
            sql.append(" and operate_date between ? and ? ");
            argList.add(datetimeStart);
            argList.add(datetimeEnd);
        } else if(Strings.isNullOrEmpty(datetimeStart) && !Strings.isNullOrEmpty(datetimeEnd)) {
            sql.append(" and operate_date <= ?");
            argList.add(datetimeEnd);
        }else if(!Strings.isNullOrEmpty(datetimeStart) && Strings.isNullOrEmpty(datetimeEnd)) {
            sql.append(" and operate_date >= ?");
            argList.add(datetimeStart);
        }
        sql.append(" order by operate_date desc");
        List<BizLog> bizLogList = getJdbcTemplate().query(sql.toString(), argList.toArray(), new BizLog());
        sql.append(" limit ?,?");

        argList.add(openPage.getFirst()-1);
        argList.add(openPage.getPageSize());
        List<BizLog> bizLogListLimit = getJdbcTemplate().query(sql.toString(), argList.toArray(), new BizLog());
        openPage.setRows(bizLogListLimit);
        openPage.setTotal(bizLogList.size());
        return openPage;
    }

    @Override
    public BizLog getById(String id) {
        StringBuilder sql = new StringBuilder(" select id,company_id,operator_id,operator_type,operate_date,content,application_id,module_id,ip_address,visible");
        sql.append(" from t_biz_log where id = ?");
        List<BizLog> bizLogList = getJdbcTemplate().query(sql.toString(), new BizLog(), id);
        if(CollectionUtils.isEmpty(bizLogList)) {
            return null;
        } else {
            return bizLogList.get(0);
        }
    }


    @Override
    public List<BizLog> getByIds(List<String> ids) {
        StringBuilder sql  = new StringBuilder(" select id,company_id,operator_id,operator_type,operate_date,content,application_id,module_id,ip_address,visible");
        sql.append(" from t_biz_log where id in (:ids)");
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate());
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("ids", ids);
        List<BizLog> bizLogList = namedParameterJdbcTemplate.query(sql.toString(), parameters, new BizLog());
        return bizLogList;
    }

    @Override
    public String update(final BizLog bizLog) {
        StringBuilder sql = new StringBuilder(" update t_biz_log set company_id=?,operator_id=?,operator_type=?,operate_date=?,content=?,");
        sql.append(" application_id=?,module_id=?,ip_address=?,visible=? where id = ?");
        int status = getJdbcTemplate().update(sql.toString(), new PreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                int i = 0;
                ps.setString(++i, bizLog.getCompanyId());
                ps.setString(++i, bizLog.getOperatorId());
                ps.setLong(++i, bizLog.getOperatorType());
                ps.setString(++i, bizLog.getOperateDate());
                ps.setString(++i, bizLog.getContent());
                ps.setString(++i, bizLog.getApplicationId());
                ps.setString(++i, bizLog.getModuleId());
                ps.setString(++i, bizLog.getIpAddress());
                ps.setBoolean(++i, bizLog.isVisible());
                ps.setString(++i, bizLog.getId());
            }

        });

        if(status > 0) {
            return bizLog.getId();
        } else {
            return Message.ERROR;
        }
    }

    @Override
    public String delete(final List<String> ids) {
        StringBuilder sql = new StringBuilder(" delete from t_biz_log where id = ?");
        int[] status = getJdbcTemplate().batchUpdate(sql.toString(), new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1,ids.get(i));
            }

            @Override
            public int getBatchSize() {
                return ids.size();
            }
        });

        if(status.length > 0) {
            return Message.SUCCESS;
        } else {
            return Message.ERROR;
        }
    }

    @Override
    public String delete(String id) {
        StringBuilder sql = new StringBuilder(" delete from t_biz_log where id = ?");
        int status = getJdbcTemplate().update(sql.toString(), id);
        if(status > 0) {
            return Message.SUCCESS;
        } else {
            return Message.ERROR;
        }
    }

    @Override
    public String save(final BizLog bizLog) {
        StringBuilder sql = new StringBuilder(" insert into t_biz_log (id,company_id,operator_id,operator_type,operate_date,content,application_id,module_id,ip_address,visible)");
        sql.append(" values(?,?,?,?,?,?,?,?,?,?)");
        int status = getJdbcTemplate().update(sql.toString(), new PreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                int i = 0;
                ps.setString(++i, bizLog.getId());
                ps.setString(++i, bizLog.getCompanyId());
                ps.setString(++i, bizLog.getOperatorId());
                ps.setLong(++i, bizLog.getOperatorType());
                ps.setString(++i, bizLog.getOperateDate());
                ps.setString(++i, bizLog.getContent());
                ps.setString(++i, bizLog.getApplicationId());
                ps.setString(++i, bizLog.getModuleId());
                ps.setString(++i, bizLog.getIpAddress());
                ps.setBoolean(++i, bizLog.isVisible());
            }

        });
        if(status > 0) {
            return bizLog.getId();
        } else {
            return Message.ERROR;
        }
    }


}
